package com.mrjy.common.qtz;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mrjy.common.entity.PromoteDetail;
import com.mrjy.common.entity.PromoteSettleInfo;
import com.mrjy.common.entity.TransferInfo;
import com.mrjy.common.entity.WechatSMSInfo;
import com.mrjy.common.util.SMSTemplate;
import com.mrjy.maintain.bo.IPromoteSettleInfoBo;
import com.mrjy.maintain.bo.ISMSSendInfoBo;
import com.mrjy.maintain.dao.IPromoteDetailDao;
import com.mrjy.maintain.dao.IWechatSMSInfoDao;
import com.mrjy.payment.bo.TransferPaymentBo;
import com.mrjy.payment.dao.ITransferInfoDao;
import com.mrjy.wechat.util.WeChatUtil;

/**
 * 普通推广者推广金额结算
 */
public class PromoteDetailSettlementJob {

    @Resource
    TransferPaymentBo transferPaymentBo;
    @Resource
	private IPromoteDetailDao promoteDetailDao;
    @Resource
    private ITransferInfoDao transferInfoDao;
    @Resource
    private IWechatSMSInfoDao wechatSMSInfoDao ;
    @Resource
	private ISMSSendInfoBo smsSendInfoBo;
    @Resource
	private IPromoteSettleInfoBo promoteSettleInfoBo;

    private static Logger logger = LoggerFactory.getLogger(PromoteDetailSettlementJob.class);
    		

    /**
     * @param
     * @Description: 执行任务，普通推广者推广金额结算
     */
    public void doJob() {
        //企业付款零钱到推广者微信账户
        List<PromoteDetail> proList = promoteDetailDao.checkPromoteDetailIsNotSettle();
        List<PromoteSettleInfo> promoteSettleList = new ArrayList<PromoteSettleInfo>();
        if(proList != null && proList.size() > 0){
        	int count = 0 ;
        	for (PromoteDetail info : proList) {
        		int row = weChatTransfer2User(info) ;
        		if(row == 1){
        			count += row ;
					info.setSettleStatus("1");
					promoteDetailDao.updateSettleStatusById(info);
					
					PromoteSettleInfo settleInfo = new PromoteSettleInfo();
					settleInfo.setPromoteId(info.getId());
					settleInfo.setSettleTime(new Timestamp(System.currentTimeMillis()));
					settleInfo.setDesc("已自动到账推广者微信账户");
					promoteSettleList.add(settleInfo);
        		}
                logger.debug("定时器定期结算普通推广者的推广金额 ：=================================> 以成功结算了"+ count +"条记录");
        	}
        	if(promoteSettleList!= null && promoteSettleList.size() > 0){
        		promoteSettleInfoBo.insertBatch((promoteSettleList));
        	}
        	
        }else{
        	logger.debug("定时器定期结算普通推广者的推广金额 ：=================================> 没有普通推广者待结算的记录");
        }

    }
    
    @SuppressWarnings("unchecked")
	public void doSettleAndSendWechatSMS() {
    	List<PromoteSettleInfo> promoteSettleList = new ArrayList<PromoteSettleInfo>();
    	//企业付款零钱到推广者微信账户
    	logger.debug("定时器定期结算开始--------->");
    	List<PromoteDetail> proList = promoteDetailDao.checkDailyPromoteDetailIsNotSettle();
    	if(proList != null && proList.size() > 0){
    		int count = 0 ;
    		for (PromoteDetail info : proList){
    			if(info != null && StringUtils.isNotBlank(info.getProCode())){
    				int row = weChatTransfer2User(info) ;
        			if(row == 1){
            			count += row ;
    					List<PromoteDetail> personList = promoteDetailDao.queryDailyPromoteDetailByRecommentId(info.getRecommendId());
    					if(personList !=null && personList.size() > 0){
    						for(PromoteDetail pd : personList){
    							pd.setSettleStatus("1");
    							promoteDetailDao.updateSettleStatusById(pd);
    							
    							PromoteSettleInfo settleInfo = new PromoteSettleInfo();
    							settleInfo.setPromoteId(info.getId());
    							settleInfo.setSettleTime(new Timestamp(System.currentTimeMillis()));
    							settleInfo.setDesc("已自动到账推广者微信账户");
    							promoteSettleList.add(settleInfo);
    						}
    					}
            		}
    			}
    			
    		}
    		if(promoteSettleList!= null && promoteSettleList.size() > 0){
        		promoteSettleInfoBo.insertBatch((promoteSettleList));
        	}
    		logger.debug("定时器定期结算普通推广者 ：=================================> 以成功结算了"+ count +"条记录");
    	}else{
    		logger.debug("定时器定期结算普通推广者 ：=================================> 没有普通推广者待结算的记录");
    	}
    	
    	//发送微信通知和短信
    	List<WechatSMSInfo> smsList = wechatSMSInfoDao.queryDailyUnSendSMS();
    	int sms_count = 0 ;
    	if(smsList != null && smsList.size() > 0){
    		for(WechatSMSInfo smsInfo : smsList){
    			//发送微信通知
    			boolean wechat_is_send = false ;
    			boolean sms_is_send = false ;
    			if(StringUtils.isNotBlank( smsInfo.getOpenid())){
					Map<String, Object> wechatMap = (Map<String, Object>) WeChatUtil.sendWechatTemplateMessageIncome(smsInfo.getContent() ,smsInfo.getDivideMoney()
    						, smsInfo.getTradeNo() ,smsInfo.getCompleteTime()
    						, smsInfo.getUrl(), smsInfo.getOpenid());
					if("200".equals(wechatMap.get("err_code").toString())){
						wechat_is_send = true ;
					}
    			}
    			//发送短信通知
    			if(StringUtils.isNotBlank( smsInfo.getMobilePhone())){
    				//给推广人发短信通知
					Map<String , Object> smsParamMap = new HashMap<String , Object>();
					smsParamMap.put("name", smsInfo.getUserName());
					smsParamMap.put("income", smsInfo.getDivideMoney());
					smsParamMap.put("time", smsInfo.getCompleteTime());
					smsParamMap.put("payer", smsInfo.getPayerName());
					//smsParamMap.put("total", smsInfo.getTotalIncome()) ;
					
					Map<String , Object> SmsMap = null;
					if (StringUtils.isBlank(smsInfo.getPromoterName())) {
						SmsMap = (Map<String, Object>) smsSendInfoBo.sendSMSAndAddRecord(smsInfo.getMobilePhone(), smsParamMap
								, SMSTemplate.TEMPLATE_11, "2", "0");
					}else {
						SmsMap = (Map<String, Object>) smsSendInfoBo.sendSMSAndAddRecord(smsInfo.getMobilePhone(), smsParamMap
								, SMSTemplate.TEMPLATE_12, "2", "0");
					}
					if("200".equals(SmsMap.get("err_code").toString())){
						sms_is_send = true ;
					}
    			}
    			if(wechat_is_send || sms_is_send){
    				int row = wechatSMSInfoDao.updateDailyUnSendSMSByUserId(smsInfo.getUserId());
    				sms_count += row ;
    			}
    		}
    		logger.debug("定时器定期发送的微信消息提醒和短信提醒 ：=================================> 以成功发送了"+ sms_count +"条记录");
    	}else{
    		logger.debug("定时器定期发送的微信消息提醒和短信提醒 ：=================================> 没有待发送的记录");
    	}
    	logger.debug("定时器定期结算 结束--------->");
    }
    
    private int weChatTransfer2User(PromoteDetail info ){
    	//企业付款零钱到推广者微信账户
		TransferInfo transInfo = new TransferInfo();
		transInfo.setAmount(info.getDivideMoney());
		transInfo.setPartnerTradeNo(info.getProCode().replaceAll("_", ""));
		transInfo.setUserId(info.getRecommendId());
		transInfo.setPaymentDesc("定时器合计转账--会员或课程包推广收入");
		logger.debug("【企业付款零钱到推广者微信账户】 开始 ------------->");
		@SuppressWarnings("unchecked")
		Map<String,Object> returnMap = (Map<String, Object>) transferPaymentBo.weChatTransferPay(transInfo);
		int row = 0;
		
		if(returnMap != null ){
			if("200".equals(returnMap.get("err_code"))){//付款成功
				transInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
				transInfo.setCompleteTime(Timestamp.valueOf((String) returnMap.get("paymentTime")));
				transInfo.setDisabledFlag("0");
				transInfo.setTransferStatus("1");
				transInfo.setErrCode((String) returnMap.get("err_code"));
				transInfo.setErrCodeDes((String) returnMap.get("err_code_des"));
				transInfo.setPaymentId(info.getPaymentId());
				row = transferInfoDao.insert(transInfo);
			}else{//付款失败
				transInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
				transInfo.setDisabledFlag("0");
				transInfo.setTransferStatus("0");
				transInfo.setErrCode((String) returnMap.get("err_code"));
				transInfo.setErrCodeDes((String) returnMap.get("err_code_des"));
				transInfo.setPaymentId(info.getPaymentId());
				transferInfoDao.insert(transInfo);
			}
		}else {
			transInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
			transInfo.setDisabledFlag("0");
			transInfo.setTransferStatus("0");
			transInfo.setErrCode("100");
			transInfo.setErrCodeDes("企业付款时没有返回map");
			transInfo.setPaymentId(info.getPaymentId());
			transferInfoDao.insert(transInfo);
		}
		logger.debug("【企业付款零钱到推广者微信账户】  err_code={},err_code_des={},partnerTradeNo={}",returnMap.get("err_code"),returnMap.get("err_code_des"),returnMap.get("partnerTradeNo"));
		logger.debug("【企业付款零钱到推广者微信账户】 结束 ------------->");
		return row ;
    }
}